<?php
	function save_times($ClockTimeOp) { 
	
	$CurrentTimeClock = date("Y-m-d H:i:s");
	$CurrentDay = date("w");
	$CurrentTimeClockDay = date("Y-m-d");
	
	$QClockProfile = "SELECT 
						timeclock_ttables.ref AS TableRef
					FROM timeclock_profiles 
						INNER JOIN timeclock_ttables ON timeclock_ttables.ref = timeclock_profiles.mon{$CurrentDay}
						WHERE main_users_ref = {$_SESSION['UtID']}";
	$ClockProfile = $GLOBALS['CONN']->db_array($QClockProfile); 
	if (isset($ClockProfile[1])) {
	$QMainTime = "SELECT
						timeclock_operations.ref,
						timeclock_operations.InTime,
						timeclock_operations.Breaks
				FROM timeclock_operations 
				WHERE main_users_ref = {$_SESSION['UtID']}
				AND DATE(time_main) = DATE('{$CurrentTimeClock}')
				ORDER BY time_main DESC LIMIT 0,1";
	$MainTime = $GLOBALS['CONN']->db_array($QMainTime); 
		if (!isset($MainTime[1])) {
		
		$QCreateInTime = "INSERT INTO timeclock_operations 
		(main_users_ref, time_main, InTime, RefTTable) 
		VALUES 
		({$_SESSION['UtID']},'{$CurrentTimeClock}','{$CurrentTimeClock}',{$ClockProfile[1]['TableRef']})";
		$CreateInTime = $GLOBALS['CONN']->db_query($QCreateInTime); 
		
		} elseif (isset($MainTime[1]) && $MainTime[1]['InTime'] == '') {
		
		$QCreateInTime = "UPDATE timeclock_operations 
		SET InTime = '{$CurrentTimeClock}' WHERE ref = {$MainTime[1]['ref']}";
		$CreateInTime = $GLOBALS['CONN']->db_query($QCreateInTime); 
		
		} else {
		
			if ($ClockTimeOp == 'EndDay') {
			
			$QChangeTime = "UPDATE timeclock_operations SET OutTime = '{$CurrentTimeClock}' ";
			
			} elseif ($ClockTimeOp == 'StartLunch') {
			
			$QChangeTime = "UPDATE timeclock_operations SET LunchStart = '{$CurrentTimeClock}' ";
			
			} elseif ($ClockTimeOp == 'EndLunch') {
			
			$QChangeTime = "UPDATE timeclock_operations SET LunchEnd = '{$CurrentTimeClock}' ";
			
			} elseif ($ClockTimeOp == 'StartBreak') {
			
			$UpdateBreak = $MainTime[1]['Breaks'].$CurrentTimeClock.";";
			$QChangeTime = "UPDATE timeclock_operations SET Breaks = '{$UpdateBreak}' ";
			
				$QOff = "INSERT INTO timeclock_delays 
				(main_user_ref, delaylevel, EventTime, Status, Justify, RefType, RefOperation)
				VALUES
				({$_SESSION['UtID']},0,'{$CurrentTimeClock}',1,'',3,{$MainTime[1]['ref']})";
				$GLOBALS['CONN']->db_query($QOff);
			
			} elseif ($ClockTimeOp == 'StartOverTime') {
			
			$QChangeTime = "UPDATE timeclock_operations SET PostTimeStart = '{$CurrentTimeClock}' ";
			
			} elseif ($ClockTimeOp == 'EndOverTime') {
			
			$QChangeTime = "UPDATE timeclock_operations SET PostTimeEnd = '{$CurrentTimeClock}' ";
			}
			if (isset($ClockTimeOp) && $ClockTimeOp != "InitSetDay" && $ClockTimeOp != "EndDayT") {
			$QChangeTime .= "WHERE ref = {$MainTime[1]['ref']}";
			$ChangeTime = $GLOBALS['CONN']->db_query($QChangeTime); 
			}
			
		}
	  }
	}
?>